/*
 *   Copyright 2023 <a href="mailto:asialjim@hotmail.com">Asial Jim</a>
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.asialjim.encommunicate.rsa.server.filter;

import com.asialjim.encommunicate.rsa.filter.ApplicationEnDecryptChecker;
import com.asialjim.encommunicate.rsa.filter.SimpleRSAFilter;
import com.asialjim.encommunicate.rsa.management.key.RSAKeyLookUpComponent;
import com.asialjim.encommunicate.rsa.server.config.RSAConfigProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;

import java.util.List;
import java.util.Objects;

/**
 * RSA 加解密过滤器配置
 *
 * @author Copyright © <a href="mailto:asialjim@hotmail.com">Asial Jim</a>   Co., LTD
 * @version 1.0
 * @since 2023/2/28, &nbsp;&nbsp; <em>version:1.0</em>, &nbsp;&nbsp; <em>java version:17</em>
 */
@Order
@Configuration
public class RSAEncryptFilterLastConfiguration {
    @Autowired private RSAKeyLookUpComponent lookUpComponent;
    @Autowired(required = false) private RSAConfigProperty configProperty;
    @Autowired(required = false) private ApplicationEnDecryptChecker enDecryptChecker;

    @Bean("securityFilterRegistrationBean")
    public FilterRegistrationBean<SimpleRSAFilter> securityFilterRegistrationBean() {
        FilterRegistrationBean<SimpleRSAFilter> bean = new FilterRegistrationBean<>();
        if (Objects.nonNull(configProperty)) {
            bean.setFilter(new SimpleRSAFilter(lookUpComponent, enDecryptChecker));
            List<String> urlPatterns = configProperty.getUrlPatterns();
            urlPatterns.forEach(bean::addUrlPatterns);
            bean.addInitParameter("apiFilterEnabled", String.valueOf(configProperty.getEnable()));
            bean.setName(configProperty.getName());
            bean.setOrder(configProperty.getOrder());
        } else {
            bean.setFilter(SimpleRSAFilter.NON_RSA_FILTER);
            bean.addInitParameter("apiFilterEnabled",String.valueOf(true));
            bean.addUrlPatterns("/*");
            bean.setName("DefaultRSAFilter");
            bean.setOrder(Integer.MIN_VALUE);
        }
        return bean;
    }
}